package cn.tedu.tmall.admin.content.controller;

import cn.tedu.tmall.admin.content.pojo.param.ArticleAddParam;
import cn.tedu.tmall.admin.content.pojo.vo.ArticleDetailVO;
import cn.tedu.tmall.admin.content.pojo.vo.ArticleVO;
import cn.tedu.tmall.admin.content.service.IArticleService;
import cn.tedu.tmall.common.pojo.po.CurrentUser;
import cn.tedu.tmall.common.pojo.vo.PageData;
import cn.tedu.tmall.common.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 学茶网-管理端-文章控制器
 */
@Api(tags = "管理端文章模块")
@Slf4j
@Validated
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private IArticleService articleService;

    /**
     * 新增文章
     * @param articleAddParam 文章详情
     */
    //业务逻辑：验证登录状态、文章标题不能重复、类别是否存在、类别状态（是否禁用）
    //save保存，返回成功或异常信息
    @ApiOperation("新增文章")
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('/article/add')")
    public JsonResult addArticle(@RequestBody @Validated ArticleAddParam articleAddParam){
        log.debug("Controller-增加文章-入参:{}",articleAddParam);
        articleService.addArticle(articleAddParam);
        log.debug("Controller-增加文章-出参:{}",JsonResult.ok());
        return JsonResult.ok();
    }

    /**
     * 通过分类id查询文章列表
     */
    //todo 前端的知道当前是第几页,还能不能分页 接口出参需要调整,后端需要计算
    //limit 0,2  pageNum 页数 pageSize 每页多少条 limit pageName,pageSize
    @ApiOperation("文章列表")
    @GetMapping("/list")
    public JsonResult list(Long categoryId,
                           @Range(min = 1,max = 20) Integer pageNum,
                           @Range(min = 1,max = 20) Integer pageSize){
        PageData<ArticleVO> articleVOS = articleService.list(categoryId,pageNum,pageSize);
        return JsonResult.ok(articleVOS);
    }

    /**
     * 文章详情
     */
    @ApiOperation("文章详情")
    @GetMapping("/detail")
    @PreAuthorize("hasAuthority('/article/detail')")
    public JsonResult detail(Long articleId){
        ArticleDetailVO detail = articleService.detail(articleId);
        return JsonResult.ok(detail);
    }

    @GetMapping("/current/user")
    @ApiOperation("识别当事人")
    public String principal(@ApiIgnore @AuthenticationPrincipal CurrentUser user) {
        return "成功处理请求：需要通过认证，且识别当事人：" + user;
    }
}
